import React, { useEffect, useState } from "react";
import ContentTop from '../../../components/ContentTop'
import { goodsInfo, goodsImgUpload, cateCategories, goodsEdit } from "../../../api/account";
import {
    Form,
    Input,
    Button,
    Select,
    InputNumber,
    Upload,
    message,
} from 'antd';
import { useLocation, useNavigate } from 'react-router-dom';

export default function GoodsEdit() {
    const navigate = useNavigate();
    const location = useLocation();
    const queryParams = new URLSearchParams(location.search);
    const id = queryParams.get('id');

    const { TextArea } = Input;
    const [datasList, setDatasList] = useState([]);
    const [imgUrl, setImgUrl] = useState("");
    const [oldImgUrl, setOldImgUrl] = useState("");
    const [imgUrl1, setImgUrl1] = useState("");
    const [imgItem, setImgItem] = useState("");
    const [goodsInfoData, setGoodsInfoData] = useState({});
    //确认数据是否加载完成
    const [isDataLoaded, setIsDataLoaded] = useState(false);

    const [form] = Form.useForm();
    const layout = {
        labelCol: {
            span: 2,
        },
    };
    const tailLayout = {
        wrapperCol: {
            offset: 2,
        },
    };

    //分类获取
    const fetchData = async () => {
        const res = await cateCategories();
        setDatasList(res.data.categories);
    }
    useEffect(() => {
        fetchData();
    }, []);

    const { Option } = Select;

    //获取单个商品信息
    const goodsData = async () => {
        let res = await goodsInfo({ id: id });

        setGoodsInfoData(res.data.data)
        setIsDataLoaded(true);

        setImgUrl(`http://8.137.157.16:9002${res.data.data.imgUrl}`);

        setOldImgUrl(`http://8.137.157.16:9002${res.data.data.imgUrl}`);
        let index = res.data.data.imgUrl.lastIndexOf('/');
        setImgUrl1(res.data.data.imgUrl.substring(index + 1));
    }
    useEffect(() => {
        goodsData();
    }, []);

    //图片修改
    const handleChange = async ({ file }) => {
        const formData = new FormData();
        formData.append('file', file);
        await goodsImgUpload(formData);
    };

    const onFinish = async (values) => {
        const data = {
            name: values.name,
            category: values.category,
            price: values.price,
            imgUrl: imgUrl == oldImgUrl ? imgUrl1 : imgItem,
            goodsDesc: values.goodsDesc,
            id: goodsInfoData.id
        }
        let res = await goodsEdit(data);
        let { code, msg } = res.data;
        if (code === 0) {
            setTimeout(() => {
                navigate('/goods');
            }, 1000);
            message.success(msg);
        } else {
            message.error(msg);
        }
    };

    return (
        <>
            <div className="app-content">
                <ContentTop>
                    <div className="title">
                        商品编辑
                    </div>
                </ContentTop>

                <div className="content-info">
                    {isDataLoaded && (
                        <Form
                            initialValues={{
                                name: goodsInfoData.name,
                                category: goodsInfoData.category,
                                price: goodsInfoData.price,
                                goodsDesc: goodsInfoData.goodsDesc
                            }}
                            {...layout}
                            form={form}
                            onFinish={onFinish}
                        >
                            <Form.Item
                                name="name"
                                label="商品名称"
                            >
                                <Input style={{
                                    width: '100%',
                                    height: 40,
                                }}
                                />

                            </Form.Item>
                            <Form.Item
                                name="category"
                                label="商品分类"
                            >
                                <Select
                                    placeholder="请选择商品分类"
                                    allowClear
                                    style={{
                                        width: 240,
                                        height: 40,
                                    }}
                                >
                                    {
                                        datasList.map(option => {
                                            return (
                                                <Option value={option.cateName} key={option.key}>
                                                    {option.cateName}
                                                </Option>
                                            )
                                        })}
                                </Select>
                            </Form.Item>
                            <Form.Item
                                label="商品价格"
                                name="price"
                            >
                                <InputNumber size="large" min={0} />
                            </Form.Item>

                            <Form.Item
                                label="商品图片"
                                name="imgUrl"
                            >
                                <Upload
                                    accept="image/png, image/jpeg"
                                    customRequest={handleChange}
                                    listType="picture-card"
                                    showUploadList={false}
                                >
                                    {imgUrl ? (
                                        <img src={imgUrl} alt="" style={{ width: 105, height: 105 }} />
                                    ) : (<button
                                        style={{
                                            border: 0,
                                            background: 'none',
                                        }}
                                        type="button"
                                    >
                                    </button>)}
                                </Upload>
                            </Form.Item>
                            <Form.Item
                                label="商品描述"
                                name="goodsDesc"
                            >
                                <TextArea rows={4} />
                            </Form.Item>

                            <Form.Item {...tailLayout}>
                                <Button type="primary" htmlType="submit" style={{ width: 100, height: 40 }}>
                                    立即修改
                                </Button>
                            </Form.Item>
                        </Form>)}
                </div>
            </div>
        </>
    )
}
